﻿using AgileConfig.Client;
using Microsoft.Extensions.Options;
using Quickly.Certs.EntityFrameworkCore;

namespace Quickly.Certs.WebApi
{
    public static class BuilderExtensions
    {
        /// <summary>
        /// AglieConfig
        /// </summary>
        /// <param name="configuration"></param>
        public static void ConfigureAgileConfigIfExists(this ConfigurationManager configuration)
        {
            var section = configuration.GetSection("AgileConfig");
            configuration.AddAgileConfig((ConfigClientOptions options) => section?.Bind(options));
        }

        /// <summary>
        /// 阿里云配置
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddAlibabaCloudOptions(this IServiceCollection services)
        {
            var alibabaKey = "AlibabaCloud";

            services.AddTransient<IConfigureOptions<AlibabaCloudAccessKey>>(sp =>
            {
                var config = sp.GetService<IConfiguration?>();
                return new ConfigureOptions<AlibabaCloudAccessKey>(options => config?.Bind(alibabaKey, options));
            });

            services.AddTransient<IConfigureOptions<AlibabaCloudEndpoint>>(sp =>
            {
                var config = sp.GetService<IConfiguration?>();
                return new ConfigureOptions<AlibabaCloudEndpoint>(options => config?.Bind(alibabaKey, options));
            });

            return services;
        }

        /// <summary>
        /// Alibaba DNS相关记录
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddCertsStoreQuickly(this IServiceCollection services)
        {
            services.AddScoped<IAlibabaCloudDomainRecordRepository, AlibabaCloudDomainRecordRepository>();

            return services;
        }
    }
}
